package weekMatch.one_340;

import java.util.*;

public class LeeCode_02 {
    public static void main(String[] args) {
//        System.out.println(Arrays.toString(distance(new int[]{1, 3, 1, 1, 2})));
//        System.out.println(Arrays.toString(distance(new int[]{0,5,3})));
//        System.out.println(Arrays.toString(distance(new int[]{1,1})));
        System.out.println(Arrays.toString(distance(new int[]{1,1,1})));
        System.out.println(Arrays.toString(distance(new int[]{1000000000,1000000000,1000000000})));
    }

    private static long[] distance(int[] nums) {
        Map<Integer, List<Long>> map = new HashMap<>();
        Map<Integer, Integer> map2 = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (map.containsKey(num)) {
                List<Long> list = map.get(num);
                list.add(list.get(list.size() - 1) + i);
                map2.put(i, list.size() - 1);
            } else {
                List<Long> list = new ArrayList<>();
                list.add((long) i);
                map.put(num, list);
                map2.put(i, list.size() - 1);
            }
        }
        long[] ans = new long[nums.length];
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            List<Long> list = map.get(num);
            int len = list.size();
            if (list.size() == 1) {
                ans[i] = 0;
            } else {
                long res = 0;
                int index = map2.get(i);
                if (index > 0)
                    res += (long) i * index - list.get(index - 1);
                if (index < len - 1)
                    res += list.get(len - 1) - list.get(index) - (long) i * (len - 1 - index);
                ans[i] = res;
            }
        }
        return ans;
    }
}
